﻿using Enterprise_Store.Data;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using Windows.UI.ApplicationSettings;

// The Group Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234229

namespace Enterprise_Store
{
    /// <summary>
    /// A page that displays an overview of a single group, including a preview of the items
    /// within the group.
    /// </summary>
    public sealed partial class GroupDetailPage : Enterprise_Store.Common.LayoutAwarePage
    {
        public GroupDetailPage()
        {
            this.InitializeComponent();
            SettingsPane.GetForCurrentView().CommandsRequested += SettingCharmManager_CommandsRequested;
        }

        private void SettingCharmManager_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            if (App.displayPrivacyPolicy)
            {
                args.Request.ApplicationCommands.Clear();
                SettingsCommand cmd = new SettingsCommand("privacypolicy", "Privacy policy", (uiCommand) =>
                {
                    OpenPrivacyPolicy();
                });

                args.Request.ApplicationCommands.Add(cmd); 
                
                cmd = new SettingsCommand("getthisapp", "Get this app for your customer", (uiCommand) =>
                {
                    GetThisApp();
                });

                args.Request.ApplicationCommands.Add(cmd);
            }
        }

        private async void OpenPrivacyPolicy()
        {
            Uri uri = new Uri("http://companystore.codeplex.com/wikipage?title=Privacy&version=1");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async void GetThisApp()
        {
            Uri uri = new Uri("http://companystore.codeplex.com/");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var group = SampleDataSource.GetGroup((String)navigationParameter);
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items;
        }

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        async void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            String uri = ((SampleDataItem)e.ClickedItem).Description;

            var option = new Windows.System.LauncherOptions();
            if (((SampleDataItem)e.ClickedItem).Content != "")
            {
                option.PreferredApplicationPackageFamilyName = ((SampleDataItem)e.ClickedItem).Content;
                option.PreferredApplicationDisplayName = ((SampleDataItem)e.ClickedItem).Title;
            }
            if (uri.ToUpper().Contains("daipp://windowsStoreWin8app".ToUpper()) && !uri.ToUpper().Contains("storeid=".ToUpper()))
            {
                uri += "?storeid=" + ((SampleDataItem)e.ClickedItem).Content;
            }
            try
            {
                //If the URI is well formated go on, if not display the error message.                
                if (Uri.IsWellFormedUriString(uri, UriKind.Absolute) || uri.ToUpper().Contains("daipp://".ToUpper()))
                {
                    await Windows.System.Launcher.LaunchUriAsync(new Uri(uri), option);
                }
                else
                {
                    ((SampleDataItem)e.ClickedItem).Subtitle = String.Format(App.errorURIMessage, uri);
                    if (((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed)
                    {
                        ((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed = true;
                    }
                }
            }
            catch (FormatException)
            {
                ((SampleDataItem)e.ClickedItem).Subtitle = String.Format(App.errorURIMessage, ((SampleDataItem)e.ClickedItem).Description);
                if (((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed)
                {
                    ((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed = true;
                }
            }
        }
    }
}
